package registry;

import java.io.IOException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import org.apache.log4j.Logger;

import utility.ConfigManager;

/**
 * Ein Registry Service, der die RMI Registry startet und hosted.
 * 
 */
public class DiscoveryRegistry {

	private static Registry rmiRegistry;
	private int rmiRegistryPort;

	Logger logger = Logger.getLogger(this.getClass());
	
	public DiscoveryRegistry()
	{
		try{
			rmiRegistryPort = ConfigManager.getInstance().getInt("registryPort");
		}
		catch (Exception e) {
			rmiRegistryPort = 1099;
		}
		startRmiRegistry(rmiRegistryPort);
	}
	
	public Registry getRmiRegistry()
	{
		return this.rmiRegistry;
	}
	
	/***
	 * Startet die Java RMI Registry auf dem angegebenen Port, damit sich TestNodes dort registrieren können.
	 * @param port
	 */
	private void startRmiRegistry(int port)
	{
		try {
			if(rmiRegistry == null)
			{
				rmiRegistry = LocateRegistry.createRegistry(port);
				logger.debug("RMI registry started at " + (port < 0? "default port" : "port " + port));
			}
		} catch (Exception e) {
			 logger.error("Exception while starting RMI registry!", e);
		}
	}
	
	public static void main(String[] args) {
		DiscoveryRegistry regServer = new DiscoveryRegistry();
		try {
			System.in.read();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
